﻿using System.Web.Mvc;
using OpusSuite.Models;
using OpusSuite.Models.Model.WebAdmin;
using OpusSuite.Utility;
using System.Linq;
//using MvcMiniProfiler;

namespace OpusSuite.Controllers
{
    public class BaseController : Controller
    {
        protected BaseController()
        {
            var jqueryUTheme = "south-street";
            //var profiler = MiniProfiler.Current; // it's ok if this is null

            try
            {
                // TODO, load theme from cookie

                //using (profiler.Step("Loading base details"))
                //{
                    if (User != null && !string.IsNullOrWhiteSpace(User.Identity.Name))
                    {
                        var model = new OpusSuiteModel(WebUtil.ServerTypeFromCookie(), WebUtil.ConnectionStringFromCookie());
                            //model.AddApplicationMessage(Enums.ApplicationMessageType.Message,
                            //                            Enums.ApplicationMessageLevel.Error, "tet message", "test dwesc",
                            //                            new User());

                            // TODO
                            // maybe use some sort of session state for the theme to save lookups
                            // on something that will infrequently change?
                            //using (profiler.Step("Loading base theme"))
                            //{
                            if (!string.IsNullOrWhiteSpace(WebUtil.UserNameFromCookie()))
                            {
                                User u = model.Context.Users.FirstOrDefault(x => x.UserName == User.Identity.Name);
                                if (u != null)
                                {
                                    jqueryUTheme = u.Profile.Theme.Code;
                                    if (jqueryUTheme != "south-street")
                                        WebUtil.AddThemeCookie(jqueryUTheme);
                                }
                            }
                            //}
                    }
                //}
            }
            catch
            {
                // do nothing as we may not be connected to the db
            }

            ViewBag.UiTheme = jqueryUTheme;
        }
    }
}
